package com.clock.service.impl;

import cn.hutool.core.date.DateUtil;
import com.clock.common.constant.ChickenSoupKey;
import com.clock.domain.entity.ChickenSoup;
import com.clock.mapper.ChickenSoupMapper;
import com.clock.service.ChickenSoupService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class ChickenSoupServiceImpl implements ChickenSoupService {

    @Resource
    ChickenSoupMapper chickenSoupMapper;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Transactional
    @Override
    public String getChickenSoup() {
        String s = stringRedisTemplate.opsForValue().get(ChickenSoupKey.CHICKEN_SOUP_KEY);
        if(s!=null){
            return s;
        }
        ChickenSoup chickenSoup = chickenSoupMapper.queryOne();
        if(chickenSoup == null){
            return null;
        }
        stringRedisTemplate.opsForValue().
                set(ChickenSoupKey.CHICKEN_SOUP_KEY, chickenSoup.getSoupContent(),
                        1, TimeUnit.DAYS);

        chickenSoupMapper.deleteById(chickenSoup.getSoupId());
        return chickenSoup.getSoupContent();
    }

    @Override
    public Integer addChickenSoup(ChickenSoup chickenSoup) {
        if(chickenSoup.getCreatTime() == null){
            chickenSoup.setCreatTime(DateUtil.date());
        }
        int i = chickenSoupMapper.insert(chickenSoup);
        return i;
    }

    @Override
    public Integer batchAddChickenSoup(ChickenSoup chickenSoup) {
        if(chickenSoup.getCreatTime() == null){
            chickenSoup.setCreatTime(DateUtil.date());
        }
        String[] strings = chickenSoup.getSoupContent().split(";");
        List list = new ArrayList<ChickenSoup>();
        for (String s : strings) {
            ChickenSoup chickenSoup1 = new ChickenSoup(s,DateUtil.date());
            list.add(chickenSoup1);
        }

        int insertBatch = chickenSoupMapper.insertBatch(list);

        return insertBatch;
    }

    @Override
    public Long getChickenCount() {
        Long count = chickenSoupMapper.count();
        return count;
    }


}
